/**
 * @file main_unified.cpp
 * @brief Unified main program for both CBP and Workspace processing
 * @author AI Assistant
 * @date 2025-10-13
 * @version 2.0
 */

#include "workspace_parser.h"
#include <wx/cmdline.h>
#include <wx/dir.h>
#include <wx/filefn.h>

// 扩展的命令行参数
static const wxCmdLineEntryDesc g_cmdLineDesc[] = {
    { wxCMD_LINE_SWITCH, "h", "help", "显示帮助信息", wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
    { wxCMD_LINE_SWITCH, "v", "version", "显示版本信息", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
    { wxCMD_LINE_OPTION, "m", "mode", "操作模式: cbp, workspace, auto", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
    { wxCMD_LINE_SWITCH, "b", "batch", "批量处理目录", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
    { wxCMD_LINE_SWITCH, "r", "recursive", "递归处理子目录", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
    { wxCMD_LINE_SWITCH, "s", "silent", "静默模式", wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL },
    { wxCMD_LINE_PARAM, nullptr, nullptr, "输入文件或目录", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
    { wxCMD_LINE_NONE }
};

// 版本信息
void ShowVersion() {
    wxPrintf("cbp2make_ai Unified Processor v2.0\n");
    wxPrintf("支持格式: .cbp, .workspace\n");
    wxPrintf("编译时间: %s\n", __DATE__);
    wxPrintf("作者: 长沙优易软件开发有限公司 李国斌 & DeepSeek\n");
}

// 自动检测文件类型
wxString DetectFileType(const wxString& input) {
    if (wxDirExists(input)) {
        return "directory";
    }
    
    wxString ext = wxFileName(input).GetExt().Lower();
    
    if (ext == "workspace" || ext == "cbworkspace") {
        return "workspace";
    } else if (ext == "cbp") {
        return "cbp";
    }
    
    return "unknown";
}

// 处理单个CBP文件
bool ProcessCBPFile(const wxString& cbpFile, bool silent = false) {
    if (!silent) wxPrintf("🔧 处理CBP项目: %s\n", cbpFile);
    
    if (!wxFileExists(cbpFile)) {
        if (!silent) wxPrintf("❌ CBP文件不存在: %s\n", cbpFile);
        return false;
    }

    // 调用原有的CBP处理逻辑
    wxString command = wxString::Format(
        "cbp2make_ai.exe --ai-mode cbp2make_aicoder \"%s\"", 
        cbpFile
    );
    
    long result = wxExecute(command, wxEXEC_SYNC | wxEXEC_NOHIDE);
    if (result == 0) {
        if (!silent) wxPrintf("✅ CBP处理成功: %s\n", cbpFile);
        return true;
    } else {
        if (!silent) wxPrintf("❌ CBP处理失败: %s (错误码: %ld)\n", cbpFile, result);
        return false;
    }
}

// 处理单个Workspace文件
bool ProcessWorkspaceFile(const wxString& workspaceFile, bool silent = false) {
    if (!silent) wxPrintf("🏢 处理Workspace: %s\n", workspaceFile);
    
    WorkspaceParser parser;
    if (!parser.ParseWorkspace(workspaceFile)) {
        if (!silent) wxPrintf("❌ 解析Workspace失败: %s\n", workspaceFile);
        return false;
    }
    
    if (!silent) wxPrintf("📊 发现 %d 个项目在Workspace中\n", parser.GetProjects().size());
    
    if (parser.GenerateWorkspaceComments(silent)) {
        auto stats = parser.GetStatistics();
        if (!silent) {
            wxPrintf("✅ Workspace处理完成: %s\n", workspaceFile);
            wxPrintf("   处理时间: %.2f秒, 项目数: %d\n", 
                     stats.processingTime, stats.totalProjects);
        }
        return true;
    } else {
        if (!silent) wxPrintf("❌ Workspace处理失败: %s\n", workspaceFile);
        return false;
    }
}

// 批量处理目录
bool ProcessBatchDirectory(const wxString& directory, bool recursive, bool silent) {
    if (!silent) wxPrintf("📁 批量处理目录: %s\n", directory);
    
    if (!wxDirExists(directory)) {
        if (!silent) wxPrintf("❌ 目录不存在: %s\n", directory);
        return false;
    }
    
    wxArrayString cbpFiles, workspaceFiles;
    
    // 查找文件
    wxDir dir(directory);
    wxString filename;
    
    // 查找CBP文件
    bool cont = dir.GetFirst(&filename, "*.cbp", wxDIR_FILES);
    while (cont) {
        cbpFiles.Add(dir.GetNameWithSep() + filename);
        cont = dir.GetNext(&filename);
    }
    
    // 查找Workspace文件
    cont = dir.GetFirst(&filename, "*.workspace", wxDIR_FILES);
    while (cont) {
        workspaceFiles.Add(dir.GetNameWithSep() + filename);
        cont = dir.GetNext(&filename);
    }
    
    if (!silent) {
        wxPrintf("📋 发现文件: %d 个CBP, %d 个Workspace\n", 
                 cbpFiles.size(), workspaceFiles.size());
    }
    
    int successCount = 0;
    int totalFiles = cbpFiles.size() + workspaceFiles.size();
    
    // 处理Workspace文件
    for (const auto& workspaceFile : workspaceFiles) {
        if (ProcessWorkspaceFile(workspaceFile, silent)) {
            successCount++;
        }
    }
    
    // 处理CBP文件
    for (const auto& cbpFile : cbpFiles) {
        if (ProcessCBPFile(cbpFile, silent)) {
            successCount++;
        }
    }
    
    // 递归处理子目录
    if (recursive) {
        cont = dir.GetFirst(&filename, "", wxDIR_DIRS | wxDIR_HIDDEN);
        while (cont) {
            // 跳过 . 和 .. 目录
            if (filename != "." && filename != "..") {
                wxString subDir = dir.GetNameWithSep() + filename;
                if (ProcessBatchDirectory(subDir, recursive, silent)) {
                    // 不增加successCount，因为递归调用已经统计了
                }
            }
            cont = dir.GetNext(&filename);
        }
    }
    
    if (!silent) {
        wxPrintf("📈 批量处理完成: %d/%d 成功\n", successCount, totalFiles);
    }
    
    return successCount > 0;
}

// 主处理函数
bool ProcessInput(const wxString& input, const wxString& mode, bool batch, bool recursive, bool silent) {
    if (batch || wxDirExists(input)) {
        return ProcessBatchDirectory(input, recursive, silent);
    }
    
    // 单个文件处理
    wxString fileType = mode;
    if (fileType == "auto") {
        fileType = DetectFileType(input);
    }
    
    if (fileType == "workspace") {
        return ProcessWorkspaceFile(input, silent);
    } else if (fileType == "cbp") {
        return ProcessCBPFile(input, silent);
    } else {
        if (!silent) wxPrintf("❌ 未知文件类型: %s\n", input);
        return false;
    }
}

int main(int argc, char** argv) {
    wxInitialize();
    
    wxCmdLineParser parser(argc, argv);
    parser.SetDesc(g_cmdLineDesc);
    parser.SetSwitchChars("-");
    
    int parseResult = parser.Parse();
    if (parseResult != 0) {
        return parseResult;
    }
    
    // 显示版本信息
    if (parser.Found("v")) {
        ShowVersion();
        wxUninitialize();
        return 0;
    }
    
    // 显示帮助信息
    if (parser.Found("h") || parser.GetParamCount() == 0) {
        parser.Usage();
        wxUninitialize();
        return 0;
    }
    
    wxString input = parser.GetParam(0);
    wxString mode = "auto";
    bool batch = parser.Found("b");
    bool recursive = parser.Found("r");
    bool silent = parser.Found("s");
    
    parser.Found("m", &mode);
    
    if (!silent) {
        wxPrintf("🚀 cbp2make_ai Unified Processor 启动\n");
        wxPrintf("==========================================\n");
        wxPrintf("输入: %s\n", input);
        wxPrintf("模式: %s\n", mode);
        wxPrintf("批量: %s\n", batch ? "是" : "否");
        wxPrintf("递归: %s\n", recursive ? "是" : "否");
        wxPrintf("静默: %s\n", silent ? "是" : "否");
        wxPrintf("==========================================\n");
    }
    
    bool success = ProcessInput(input, mode, batch, recursive, silent);
    
    if (!silent) {
        wxPrintf("\n%s 处理完成!\n", success ? "✅" : "❌");
    }
    
    wxUninitialize();
    return success ? 0 : 1;
}
